from rest_framework import serializers
from django.utils import timezone
import re

from users.models import User


class AdminAuthSerializer(serializers.ModelSerializer):
    """管理员登录序列化器类"""
    token = serializers.CharField(label='JWT token', read_only=True)
    username = serializers.CharField(label='用户名')

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'token')

        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    # 补充验证
    def validate(self, attrs):
        """用户名和密码正确"""
        username = attrs['username']
        password = attrs['password']

        try:
            user = User.objects.get(username=username, is_staff=True)
        except User.DoesNotExist:
            raise serializers.ValidationError('用户名或密码错误')

        if not user.check_password(password):

            raise serializers.ValidationError('用户名或密码错误')

        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        # 生成jwt token，保存登录用户身份信息
        user = validated_data['user']
        #
        user.last_login = timezone.now()

        user.save()

        from rest_framework_jwt.settings import api_settings

        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)
        print(token)

        # 给user对象增加属性，保存jwt token的数据
        user.token = token

        return user


# 定义用户序列化器类
class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')

    extra_kwargs = {
        'username': {
            'minlength': 5,
            'maxlength': 20,
            'error_messages': {
                'minlength': '最小长度为5',
                'maxlength': '最大长度为20'
            }
        },
        'password': {
            'write_only': True,
            'minlength': 8,
            'maxlength': 20,
            'error_messages': {
                'minlength': '最小长度为8',
                'maxlength': '最大长度为20'
            }
        }
    }

    def validate_password(self,value):
        # 密码校验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',value):
            raise serializers.ValidationError('密码为5-20个字母或数字')
        return value

    def validate_mobile(self,value):
        # 手机号码校验
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号格式错误')

        count = User.objects.filter(mobile=value).count()

        if count > 0:
            raise serializers.ValidationError('手机号以存在')

        return value

    # 创建用户
    def create(self, validated_data):

        user = User.objects.create_user(**validated_data)

        return user









